package com.bvgol.examples.springbootdocker.controller;

import com.bvgol.examples.springbootdocker.model.User;
import com.bvgol.examples.springbootdocker.service.UserService;
import com.bvgol.examples.springbootdocker.utils.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@RestController("/helloDocker")
public class HelloDockerController {

    @Value(value = "${server.port}")
    private String port;

    @Autowired
    private UserService userService;

    @Autowired
    private RedisUtil redisUtil;

    @GetMapping("/get/{str}")
    public String get(@PathVariable("str") String str) {
        return port + "----" + str + LocalDateTime.now();
    }

    @GetMapping("/getUserFromMysql/{id}")
    public User getUserFromMysql(@PathVariable("id") String id) {
        return userService.getById(id);
    }

    @GetMapping("/getUserFromRedis/{id}")
    public Object getUserFromRedis(@PathVariable("id") String id) {
        return redisUtil.get(id);
    }

    @PostMapping("postUser2Mysql")
    public Object postUser2Mysql(@RequestBody User user) {
        boolean save = userService.save(user);
        boolean set = redisUtil.set(user.getUserId() + "", user);

        return save == set;
    }

    /**
     * @param
     * @param null
     * @return
     * @Classname
     * @Description java 正则表达式回溯造成 CPU 100%
     * @Date 2021/6/10 14:42
     * @auther by GUOCHEN
     */
    @PostMapping("RegexLoad ")
    public Object RegexLoad(@RequestBody Object obj) {
        String[] patternMatch = {"([\\w\\s]+)+([+\\-/*])+([\\w\\s]+)",
                "([\\w\\s]+)+([+\\-/*])+([\\w\\s]+)+([+\\-/*])+([\\w\\s]+)"};
        List<String> patternList = new ArrayList();

        patternList.add("Avg Volume Units product A + Volume Units product A");
        patternList.add("Avg Volume Units /  Volume Units product A");
        patternList.add("Avg retailer On Hand / Volume Units Plan / Store Count");
        patternList.add("Avg Hand Volume Units Plan Store Count");
        patternList.add("1 - Avg merchant Volume Units");
        patternList.add("Total retailer shipment Count");

        for (String s : patternList) {

            for (int i = 0; i < patternMatch.length; i++) {
                Pattern pattern = Pattern.compile(patternMatch[i]);

                Matcher matcher = pattern.matcher(s);
                System.out.println(s);
                if (matcher.matches()) {

                    System.out.println("Passed");
                } else {
                    System.out.println("Failed;");
                }
            }
        }

        return obj;
    }

}
